﻿using System.Collections.ObjectModel;

namespace Gmantis.Controls.Chart
{
    public class AxisCollection : Collection<Axis>
    {
        // Fields
        private ChartView _view;

        // Methods
        protected override void ClearItems()
        {
            while (base.Count > 2)
            {
                this.RemoveItem(base.Count - 1);
            }
        }

        private string GetUniqueName(string prefix)
        {
            string str = "";
            int num = 1;
            while (true)
            {
                str = prefix + num;
                if (this[str] == null)
                {
                    return str;
                }
                num++;
            }
        }

        protected override void InsertItem(int index, Axis item)
        {
            base.InsertItem(index, item);
            this._view.AddAxis(item);
            ChartViewport2D viewElement = this._view.ViewElement as ChartViewport2D;
            if (viewElement != null)
            {
                viewElement.AddAxis(item);
            }
            this.UpdateChart();
        }

        protected override void RemoveItem(int index)
        {
            if (index >= 2)
            {
                ChartViewport2D viewElement = this._view.ViewElement as ChartViewport2D;
                if (viewElement != null)
                {
                    Axis ax = base[index];
                    viewElement.RemoveAxis(ax);
                }
                this._view.RemoveAxis(base[index]);
                base.RemoveItem(index);
                this.UpdateChart();
            }
        }

        private void UpdateChart()
        {
            if (this._view.Chart != null)
            {
                this._view.Chart.forceRebuild = true;
                this._view.Chart.InvalidateChart();
            }
        }

        // Properties
        public Axis this[string name]
        {
            get
            {
                foreach (Axis axis in this)
                {
                    if (axis.Name == name)
                    {
                        return axis;
                    }
                }
                return null;
            }
        }

        internal ChartView View
        {
            set
            {
                this._view = value;
            }
        }
    }
}
